package com.liang.pcc.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.fastjson2.JSON;
import com.liang.pcc.domain.DeviceInfo;
import com.liang.pcc.domain.PowerData;
import com.liang.pcc.excel.BaseExcelListener;
import com.liang.pcc.excel.model.MainTransformerLineOperationData;
import com.liang.pcc.service.DeviceInfoService;
import com.liang.pcc.service.PowerDataService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 主变线路运行数据表监听器
 */
@Slf4j
public class MainLineDataListener extends BaseExcelListener<Map<Integer, String>> {

    private final List<MainTransformerLineOperationData> dataList = new ArrayList<>();
    private final Long fileId;
    private final Long userId;
    private final PowerDataService powerDataService;
    private final DeviceInfoService deviceInfoService;

    // 存储时间列索引（例如：3 -> 00:00, 4 -> 00:15）
    private final Map<Integer, String> timeColumnMap = new HashMap<>();

    public MainLineDataListener(PowerDataService powerDataService, DeviceInfoService deviceInfoService, CountDownLatch latch, Long fileId, Long userId) {
        super(latch);
        this.fileId = fileId;
        this.userId = userId;
        this.powerDataService = powerDataService;
        this.deviceInfoService = deviceInfoService;
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        headMap.forEach((colIndex, cell) -> {
            if (colIndex >= 3) {
                String timeStr = cell.getStringValue();
                timeColumnMap.put(colIndex, timeStr);
            }
        });
        log.info("解析到表头: {}", timeColumnMap);
    }

    @Override
    public void invoke(Map<Integer, String> rowMap, AnalysisContext context) {
        MainTransformerLineOperationData data = new MainTransformerLineOperationData();
        // 解析基础字段（序号、配置名称、D5000名称）
        data.setSerialNumber(Long.valueOf(rowMap.get(0)));
        data.setConfigName(rowMap.get(1));
        data.setD5000Name(rowMap.get(2));

        DeviceInfo deviceInfo = DeviceInfo.builder()
                .configName(data.getConfigName())
                .d5000Name(data.getD5000Name())
                .fileId(fileId)
                .userId(userId)
                .build();
        deviceInfoService.save(deviceInfo);

        // 解析动态时间列
        timeColumnMap.forEach((colIndex, time) -> {
            String powerValue = rowMap.get(colIndex);
            if (powerValue != null && !powerValue.isEmpty()) {
                try {
                    data.getTimePowerMap().put(time, Double.parseDouble(powerValue));
                } catch (NumberFormatException e) {
                    log.error("功率值格式错误，时间: {}, 值: {}", time, powerValue);
                    data.getTimePowerMap().put(time, 0.0);
                }
            }
        });
        dataList.add(data);
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        dataList.forEach(data -> {
            // 根据配置名称或 D5000 名称查询设备ID
            DeviceInfo deviceInfo = deviceInfoService.lambdaQuery()
                    .eq(DeviceInfo::getConfigName, data.getConfigName())
                    .eq(DeviceInfo::getUserId, userId)
                    .eq(DeviceInfo::getFileId, fileId)
                    .one();
            log.info("设备信息: {}", JSON.toJSONString(deviceInfo));
            List<PowerData> powerDataList = data.convertToPowerDataList(deviceInfo, fileId, userId);
            powerDataService.saveBatch(powerDataList);
        });
        // 标记数据处理完成
        super.doAfterAllAnalysed(context);
        log.info("Sheet3数据插入完成！");
    }
}